import { Clock, Shuffle, MessageSquareText, Pause as PauseIcon, RefreshCw, ChevronDown, Timer, UserPlus } from 'lucide-react'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Separator } from '@/components/ui/separator'
import { Slider } from '@/components/ui/slider'
import { Switch } from '@/components/ui/switch'
import { useAIAssist } from '@/hooks/useAIAssist'
import { Textarea } from '@/components/ui/textarea'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Badge } from '@/components/ui/badge'
import { Checkbox } from '@/components/ui/checkbox'
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible'
import { useState } from 'react'
import { PRESET_VOICES } from 'shared/constants'

export default function PlaybackConfigCard() {
  const { config, updateConfig } = useAIAssist()
  const [isOpen, setIsOpen] = useState(false)

  // 合并预设音色和自定义音色
  const allVoices = [...PRESET_VOICES, ...(config.voice.customVoices || [])]

  // 确保 playback 配置存在，提供默认值
  const playbackConfig = config.playback ?? {
    interval: { min: 3, max: 10 },
    randomization: {
      enable: false,
      speedRange: [0.9, 1.1] as [number, number],
      volumeRange: [45, 55] as [number, number],
      pitchRange: [-50, 50] as [number, number],
    },
    timeAnnouncement: { 
      enable: false, 
      interval: { min: 30, max: 60 }, 
      templates: [
        '当前时间{时间}',
        '现在是{时间}',
        '时间过得真快，一眨眼就来到了{时间}',
      ],
      mode: 'random' as const
    },
    welcomeUser: { 
      enable: false,
      interval: { min: 5, max: 10 },
      templates: [
        '欢迎{用户}',
        '欢迎{用户}来到直播间',
        '{用户}来啦，欢迎欢迎',
      ],
      mode: 'random' as const
    },
    pause: { enable: false, duration: [200, 500] as [number, number] },
  }

  return (
    <Collapsible open={isOpen} onOpenChange={setIsOpen}>
      <Card className="shadow-sm">
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <div className="flex-1">
              <CardTitle className="flex items-center gap-2">
                <Clock className="h-5 w-5" />
                播放配置
              </CardTitle>
              <CardDescription className="mt-1.5">
                配置播放间隔、随机参数等，模拟真实用户说话
              </CardDescription>
            </div>
            <CollapsibleTrigger asChild>
              <button
                type="button"
                className="ml-2 p-2 hover:bg-accent rounded-md transition-colors"
                aria-label={isOpen ? '收起' : '展开'}
              >
                <ChevronDown
                  className={`h-5 w-5 text-muted-foreground transition-transform duration-200 ${
                    isOpen ? 'transform rotate-180' : ''
                  }`}
                />
              </button>
            </CollapsibleTrigger>
          </div>
        </CardHeader>
        <CollapsibleContent>
          <Separator />
          <CardContent className="pt-4 space-y-6">
        {/* 播放间隔配置 */}
        <div className="space-y-4">
          <div className="flex items-center gap-2">
            <Clock className="h-4 w-4 text-muted-foreground" />
            <h4 className="text-sm font-medium">播放间隔</h4>
          </div>
          <div className="space-y-3 pl-6">
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-2">
                <Label htmlFor="intervalMin">最小间隔 (秒)</Label>
                <Input
                  id="intervalMin"
                  type="number"
                  min={1}
                  max={60}
                  value={playbackConfig.interval.min}
                  onChange={e =>
                    updateConfig({
                      playback: {
                        ...playbackConfig,
                        interval: {
                          ...playbackConfig.interval,
                          min: Number(e.target.value),
                        },
                      },
                    })
                  }
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="intervalMax">最大间隔 (秒)</Label>
                <Input
                  id="intervalMax"
                  type="number"
                  min={1}
                  max={60}
                  value={playbackConfig.interval.max}
                  onChange={e =>
                    updateConfig({
                      playback: {
                        ...playbackConfig,
                        interval: {
                          ...playbackConfig.interval,
                          max: Number(e.target.value),
                        },
                      },
                    })
                  }
                />
              </div>
            </div>
            <p className="text-xs text-muted-foreground mt-2 pl-6">
              💡 话术队列采用严格的先进先出（FIFO）顺序播放，确保播放顺序的确定性
            </p>
          </div>
        </div>

        <Separator />

        {/* 音色切换配置 */}
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <RefreshCw className="h-4 w-4 text-muted-foreground" />
              <h4 className="text-sm font-medium">音色切换</h4>
            </div>
            <div className="flex items-center gap-2">
              <Switch
                checked={config.voice.voiceRotation?.enable ?? false}
                onCheckedChange={checked =>
                  updateConfig({
                    voice: {
                      ...config.voice,
                      voiceRotation: {
                        ...(config.voice.voiceRotation || { interval: [5, 15], voiceIds: [] }),
                        enable: checked,
                      },
                    },
                  })
                }
              />
              <Label className="text-xs">启用</Label>
            </div>
          </div>
          {config.voice.voiceRotation?.enable && (
            <div className="space-y-3 pl-6">
              <div className="space-y-2">
                <Label>切换间隔范围 (分钟)</Label>
                <div className="grid grid-cols-2 gap-3">
                  <div className="space-y-2">
                    <Label htmlFor="rotationIntervalMin">最小间隔</Label>
                    <Input
                      id="rotationIntervalMin"
                      type="number"
                      min={1}
                      max={120}
                      value={
                        Array.isArray(config.voice.voiceRotation?.interval)
                          ? config.voice.voiceRotation.interval[0]
                          : 5
                      }
                      onChange={e =>
                        updateConfig({
                          voice: {
                            ...config.voice,
                            voiceRotation: {
                              ...config.voice.voiceRotation!,
                              interval: [
                                Number(e.target.value),
                                Array.isArray(config.voice.voiceRotation?.interval)
                                  ? config.voice.voiceRotation.interval[1]
                                  : 15,
                              ],
                            },
                          },
                        })
                      }
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="rotationIntervalMax">最大间隔</Label>
                    <Input
                      id="rotationIntervalMax"
                      type="number"
                      min={1}
                      max={120}
                      value={
                        Array.isArray(config.voice.voiceRotation?.interval)
                          ? config.voice.voiceRotation.interval[1]
                          : 15
                      }
                      onChange={e =>
                        updateConfig({
                          voice: {
                            ...config.voice,
                            voiceRotation: {
                              ...config.voice.voiceRotation!,
                              interval: [
                                Array.isArray(config.voice.voiceRotation?.interval)
                                  ? config.voice.voiceRotation.interval[0]
                                  : 5,
                                Number(e.target.value),
                              ],
                            },
                          },
                        })
                      }
                    />
                  </div>
                </div>
                <p className="text-xs text-muted-foreground">
                  在指定时间范围内随机切换音色，模拟换人更自然
                </p>
              </div>
              <div className="space-y-2">
                <Label>选择要轮换的音色</Label>
                <div className="space-y-2 max-h-48 overflow-y-auto border rounded-md p-3">
                  {/* 预设音色 */}
                  {PRESET_VOICES.length > 0 && (
                    <>
                      <div className="text-xs font-semibold text-muted-foreground mb-2">
                        预设音色
                      </div>
                      {PRESET_VOICES.map(voice => {
                        const isChecked = config.voice.voiceRotation?.voiceIds.includes(voice.id) ?? false
                        return (
                          <div key={voice.id} className="flex items-center space-x-2">
                            <Checkbox
                              id={`voice-${voice.id}`}
                              checked={isChecked}
                              onCheckedChange={checked => {
                                const currentIds = config.voice.voiceRotation?.voiceIds ?? []
                                const newIds = checked
                                  ? [...currentIds, voice.id]
                                  : currentIds.filter(id => id !== voice.id)
                                updateConfig({
                                  voice: {
                                    ...config.voice,
                                    voiceRotation: {
                                      ...config.voice.voiceRotation!,
                                      voiceIds: newIds,
                                    },
                                  },
                                })
                              }}
                            />
                            <Label
                              htmlFor={`voice-${voice.id}`}
                              className="text-sm font-normal cursor-pointer"
                            >
                              {voice.name}
                            </Label>
                          </div>
                        )
                      })}
                    </>
                  )}
                  {/* 自定义音色 */}
                  {(config.voice.customVoices || []).length > 0 && (
                    <>
                      <div className="text-xs font-semibold text-muted-foreground mb-2 mt-3 pt-3 border-t">
                        自定义音色
                      </div>
                      {(config.voice.customVoices || []).map(voice => {
                        const isChecked = config.voice.voiceRotation?.voiceIds.includes(voice.id) ?? false
                        return (
                          <div key={voice.id} className="flex items-center space-x-2">
                            <Checkbox
                              id={`voice-${voice.id}`}
                              checked={isChecked}
                              onCheckedChange={checked => {
                                const currentIds = config.voice.voiceRotation?.voiceIds ?? []
                                const newIds = checked
                                  ? [...currentIds, voice.id]
                                  : currentIds.filter(id => id !== voice.id)
                                updateConfig({
                                  voice: {
                                    ...config.voice,
                                    voiceRotation: {
                                      ...config.voice.voiceRotation!,
                                      voiceIds: newIds,
                                    },
                                  },
                                })
                              }}
                            />
                            <Label
                              htmlFor={`voice-${voice.id}`}
                              className="text-sm font-normal cursor-pointer"
                            >
                              {voice.name}
                            </Label>
                          </div>
                        )
                      })}
                    </>
                  )}
                </div>
                <p className="text-xs text-muted-foreground">
                  选择多个音色进行轮换，系统会自动切换（已选择 {config.voice.voiceRotation?.voiceIds.length ?? 0} 个）
                </p>
              </div>
            </div>
          )}
        </div>

        <Separator />

        {/* 随机参数配置 */}
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Shuffle className="h-4 w-4 text-muted-foreground" />
              <h4 className="text-sm font-medium">随机化参数</h4>
            </div>
            <div className="flex items-center gap-2">
              <Switch
                checked={playbackConfig.randomization.enable}
                onCheckedChange={checked =>
                  updateConfig({
                    playback: {
                      ...playbackConfig,
                      randomization: {
                        ...playbackConfig.randomization,
                        enable: checked,
                      },
                    },
                  })
                }
              />
              <Label className="text-xs">启用</Label>
            </div>
          </div>
          {playbackConfig.randomization.enable && (
            <div className="space-y-4 pl-6">
              <div className="space-y-2">
                <Label>语速范围</Label>
                <div className="flex items-center gap-3">
                  <Input
                    type="number"
                    min={0.5}
                    max={2.0}
                    step={0.1}
                    value={playbackConfig.randomization.speedRange[0]}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...playbackConfig,
                          randomization: {
                            ...playbackConfig.randomization,
                            speedRange: [
                              Number(e.target.value),
                              playbackConfig.randomization.speedRange[1],
                            ],
                          },
                        },
                      })
                    }
                    className="w-24"
                  />
                  <span className="text-sm text-muted-foreground">至</span>
                  <Input
                    type="number"
                    min={0.5}
                    max={2.0}
                    step={0.1}
                    value={playbackConfig.randomization.speedRange[1]}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...playbackConfig,
                          randomization: {
                            ...playbackConfig.randomization,
                            speedRange: [
                              playbackConfig.randomization.speedRange[0],
                              Number(e.target.value),
                            ],
                          },
                        },
                      })
                    }
                    className="w-24"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label>音量范围</Label>
                <div className="flex items-center gap-3">
                  <Input
                    type="number"
                    min={0}
                    max={100}
                    value={playbackConfig.randomization.volumeRange[0]}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...playbackConfig,
                          randomization: {
                            ...playbackConfig.randomization,
                            volumeRange: [
                              Number(e.target.value),
                              playbackConfig.randomization.volumeRange[1],
                            ],
                          },
                        },
                      })
                    }
                    className="w-24"
                  />
                  <span className="text-sm text-muted-foreground">至</span>
                  <Input
                    type="number"
                    min={0}
                    max={100}
                    value={playbackConfig.randomization.volumeRange[1]}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...playbackConfig,
                          randomization: {
                            ...playbackConfig.randomization,
                            volumeRange: [
                              playbackConfig.randomization.volumeRange[0],
                              Number(e.target.value),
                            ],
                          },
                        },
                      })
                    }
                    className="w-24"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label>音调范围</Label>
                <div className="flex items-center gap-3">
                  <Input
                    type="number"
                    min={-500}
                    max={500}
                    step={1}
                    value={playbackConfig.randomization.pitchRange[0]}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...playbackConfig,
                          randomization: {
                            ...playbackConfig.randomization,
                            pitchRange: [
                              Number(e.target.value),
                              playbackConfig.randomization.pitchRange[1],
                            ],
                          },
                        },
                      })
                    }
                    className="w-24"
                  />
                  <span className="text-sm text-muted-foreground">至</span>
                  <Input
                    type="number"
                    min={-500}
                    max={500}
                    step={10}
                    value={playbackConfig.randomization.pitchRange[1]}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...playbackConfig,
                          randomization: {
                            ...playbackConfig.randomization,
                            pitchRange: [
                              playbackConfig.randomization.pitchRange[0],
                              Number(e.target.value),
                            ],
                          },
                        },
                      })
                    }
                    className="w-24"
                  />
                </div>
              </div>
              <p className="text-xs text-muted-foreground">
                每次播报时在指定范围内随机选择参数值，模拟真实说话
              </p>
            </div>
          )}
        </div>

        <Separator />

        {/* 报时功能 */}
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Timer className="h-4 w-4 text-muted-foreground" />
              <h4 className="text-sm font-medium">报时功能</h4>
            </div>
            <div className="flex items-center gap-2">
              <Switch
                checked={playbackConfig.timeAnnouncement?.enable ?? false}
                onCheckedChange={checked =>
                  updateConfig({
                    playback: {
                      ...playbackConfig,
                      timeAnnouncement: {
                        ...(playbackConfig.timeAnnouncement || { 
                          interval: { min: 30, max: 60 }, 
                          templates: ['当前时间{时间}', '现在是{时间}'],
                          mode: 'random' 
                        }),
                        enable: checked,
                      },
                    },
                  })
                }
              />
              <Label className="text-xs">启用</Label>
            </div>
          </div>
          {playbackConfig.timeAnnouncement?.enable && (
            <div className="space-y-3 pl-6">
              <div className="space-y-2">
                <Label>播报间隔 (分钟)</Label>
                <div className="flex items-center gap-3">
                  <Input
                    type="number"
                    min={1}
                    max={180}
                    value={playbackConfig.timeAnnouncement.interval.min}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...playbackConfig,
                          timeAnnouncement: {
                            ...playbackConfig.timeAnnouncement!,
                            interval: {
                              ...playbackConfig.timeAnnouncement!.interval,
                              min: Number(e.target.value),
                            },
                          },
                        },
                      })
                    }
                    className="w-24"
                  />
                  <span className="text-sm text-muted-foreground">至</span>
                  <Input
                    type="number"
                    min={1}
                    max={180}
                    value={playbackConfig.timeAnnouncement.interval.max}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...playbackConfig,
                          timeAnnouncement: {
                            ...playbackConfig.timeAnnouncement!,
                            interval: {
                              ...playbackConfig.timeAnnouncement!.interval,
                              max: Number(e.target.value),
                            },
                          },
                        },
                      })
                    }
                    className="w-24"
                  />
                  <span className="text-sm text-muted-foreground">分钟</span>
                </div>
                <p className="text-xs text-muted-foreground">
                  💡 报时模板可在"内容改写播放"中的"一键播报"处配置
                </p>
              </div>
            </div>
          )}
        </div>

        <Separator />

        {/* 欢迎用户功能 */}
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <UserPlus className="h-4 w-4 text-muted-foreground" />
              <h4 className="text-sm font-medium">欢迎用户</h4>
            </div>
            <div className="flex items-center gap-2">
              <Switch
                checked={playbackConfig.welcomeUser?.enable ?? false}
                onCheckedChange={checked =>
                  updateConfig({
                    playback: {
                      ...playbackConfig,
                      welcomeUser: {
                        ...(playbackConfig.welcomeUser || { 
                          interval: { min: 5, max: 10 },
                          templates: [],
                          mode: 'random' as const,
                        }),
                        enable: checked,
                      },
                    },
                  })
                }
              />
              <Label className="text-xs">启用</Label>
            </div>
          </div>
          {playbackConfig.welcomeUser?.enable && (
            <div className="space-y-3 pl-6">
              <div className="space-y-2">
                <Label>播报间隔 (秒)</Label>
                <div className="flex items-center gap-3">
                  <Input
                    type="number"
                    min={1}
                    max={300}
                    value={playbackConfig.welcomeUser.interval.min}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...playbackConfig,
                          welcomeUser: {
                            ...playbackConfig.welcomeUser!,
                            interval: {
                              ...playbackConfig.welcomeUser!.interval,
                              min: Number(e.target.value),
                            },
                          },
                        },
                      })
                    }
                    className="w-24"
                  />
                  <span className="text-sm text-muted-foreground">至</span>
                  <Input
                    type="number"
                    min={1}
                    max={300}
                    value={playbackConfig.welcomeUser.interval.max}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...playbackConfig,
                          welcomeUser: {
                            ...playbackConfig.welcomeUser!,
                            interval: {
                              ...playbackConfig.welcomeUser!.interval,
                              max: Number(e.target.value),
                            },
                          },
                        },
                      })
                    }
                    className="w-24"
                  />
                  <span className="text-sm text-muted-foreground">秒</span>
                </div>
                <p className="text-xs text-muted-foreground">
                  💡 欢迎用户模板可在"内容改写播放"中的"一键播报"处配置
                </p>
              </div>
            </div>
          )}
        </div>

        <Separator />

        {/* 停顿配置 */}
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <PauseIcon className="h-4 w-4 text-muted-foreground" />
              <h4 className="text-sm font-medium">停顿设置</h4>
            </div>
            <div className="flex items-center gap-2">
              <Switch
                checked={playbackConfig.pause.enable}
                onCheckedChange={checked =>
                  updateConfig({
                    playback: {
                      ...playbackConfig,
                      pause: {
                        ...playbackConfig.pause,
                        enable: checked,
                      },
                    },
                  })
                }
              />
              <Label className="text-xs">启用</Label>
            </div>
          </div>
          {playbackConfig.pause.enable && (
            <div className="space-y-3 pl-6">
              <div className="space-y-2">
                <Label>停顿时长范围 (毫秒)</Label>
                <div className="flex items-center gap-3">
                  <Input
                    type="number"
                    min={0}
                    max={5000}
                    step={100}
                    value={playbackConfig.pause.duration[0]}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...playbackConfig,
                          pause: {
                            ...playbackConfig.pause,
                            duration: [
                              Number(e.target.value),
                              playbackConfig.pause.duration[1],
                            ],
                          },
                        },
                      })
                    }
                    className="w-28"
                  />
                  <span className="text-sm text-muted-foreground">至</span>
                  <Input
                    type="number"
                    min={0}
                    max={5000}
                    step={100}
                    value={playbackConfig.pause.duration[1]}
                    onChange={e =>
                      updateConfig({
                        playback: {
                          ...playbackConfig,
                          pause: {
                            ...playbackConfig.pause,
                            duration: [
                              playbackConfig.pause.duration[0],
                              Number(e.target.value),
                            ],
                          },
                        },
                      })
                    }
                    className="w-28"
                  />
                </div>
                <p className="text-xs text-muted-foreground">
                  在播报间添加随机停顿，更自然
                </p>
              </div>
            </div>
          )}
        </div>
          </CardContent>
        </CollapsibleContent>
      </Card>
    </Collapsible>
  )
}

